package com.qdxwx.web.controller.user;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.user.UserWorkHistoryService;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserWorkHistory;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user/history")
public class UserWorkHistoryController extends BaseController {

    @Autowired
    private UserWorkHistoryService userWorkHistoryService;

    @PostMapping("/save.json")
    @ResponseBody
    public AjaxResult saveHistory(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.error("登录超时");
        }

        String workUnit = TKString.trim(request.getParameter("workUnit"));
        if (TKString.isEmpty(workUnit)) return AjaxResult.error("单位名称不能为空");

        String workDate = TKString.trim(request.getParameter("workDate"));
        if (TKString.isEmpty(workDate)) return AjaxResult.error("请选择您的在职时间段");

        String position = TKString.trim(request.getParameter("position"));
        if (TKString.isEmpty(position)) return AjaxResult.error("请输入您的职位");

        String workIntro = request.getParameter("workIntro");
        if (TKString.isEmpty(workIntro)) return AjaxResult.error("请输入您工作内容或经历");

        UserWorkHistory userWorkHistory = new UserWorkHistory();
        userWorkHistory.setUserId(user.getUserId());
        userWorkHistory.setWorkUnit(workUnit);
        userWorkHistory.setWorkDate(workDate);
        userWorkHistory.setPosition(position);
        userWorkHistory.setWorkIntro(workIntro);
        int row = userWorkHistoryService.insert(userWorkHistory);
        return row > 0 ? AjaxResult.success(userWorkHistory) : AjaxResult.error("系统出错，请稍后再试");
    }

    @PostMapping("/del.json")
    @ResponseBody
    public AjaxResult delHistory(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.error("登录超时");
        }
        int id = TKConvert.toInteger(request.getParameter("id"));
        if(id < 1) return AjaxResult.error("参数异常");
        UserWorkHistory history = userWorkHistoryService.get(id);
        if(history == null) return AjaxResult.error("找不到指定删除数据");
        if(history.getUserId() != user.getUserId()) return AjaxResult.error("请停止您的非法操作");
        int row = userWorkHistoryService.delete(id);
        return row > 0 ? AjaxResult.success() : AjaxResult.error("系统出错，请稍后再试");
    }


}
